<?php


namespace App\Middleware;


use App\Constants\CoContext;
use App\Constants\ContextKey;
use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Model\AdminUser;
use App\Model\Cooperative;
use App\Model\CooperativeUser;
use App\Utils\Casbin;
use App\Utils\Jwt;
use Hyperf\Utils\Context;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class CooperativeAuthMiddleware implements MiddlewareInterface
{

    /**
     * @var Casbin
     */
    protected $casbinInstace;

    public function __construct()
    {
        $this->casbinInstace = make(Casbin::class, [config('casbin.cooperative')]);
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $cooperativeUser = $this->verifyToken($request);

        $this->checkPermission($request, $cooperativeUser);

        return $handler->handle($request);
    }

    /**
     * @param ServerRequestInterface $request
     * @return \Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model|object
     */
    public function verifyToken(ServerRequestInterface &$request):CooperativeUser
    {
        if ($request->hasHeader('authorization')) {
            $token = $request->getHeaderLine('authorization');
        } else {
            // query 参数里面的token
            $queries = $request->getQueryParams();
            if (!isset($queries['authorization'])) {
                throw new BusinessException(ErrorCode::UNAUTHORIZED);
            }
            // 获取到以后过滤query中token
            $token = $queries['authorization'];
            unset($queries['authorization']);
            $request = $request->withQueryParams($queries);
        }

        $verifiedToken = Jwt::verify($token,'jwt.cooperative');

        $cooperativeUserId = $verifiedToken->getClaim('id');

        /** @var CooperativeUser $cooperativeUser */
        $cooperativeUser = CooperativeUser::query()->where('id', $cooperativeUserId)->first();

        if($cooperativeUser->cooperative->status == \App\Constants\Model\Cooperative::STATUS_BLOCKED){
            throw new BusinessException(ErrorCode::COOPERATIVE_DISABLE);
        }

        if (null == $cooperativeUser) {
            throw new BusinessException(ErrorCode::COOPERATIVE_USER_NOT_FOUND);
        }

        Context::set(ContextKey::COOPERATIVE_USER, $cooperativeUser);

        return $cooperativeUser;
    }

    public function checkPermission(ServerRequestInterface $request,CooperativeUser $user)
    {
//        if ('local' != \env('APP_ENV')) {
//            return true;
//        }

        return ;
        $userId =  $user->id;

        $path = $request->getUri()->getPath();

        $method = $request->getMethod();

        $can = $this->casbinInstace->can($userId, $path, $method);

        if(!$can){
            throw new BusinessException(ErrorCode::PERMISSION_DENIED);
        }
    }
}